<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="抽奖活动" prop="configId">
        <el-select v-model="queryParams.configId" placeholder="请选择" clearable size="small">
          <el-option
            v-for="item in configOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="奖品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="奖品类型" prop="contentType">
        <el-select v-model="queryParams.contentType" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in contentTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>

      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ypp:raffle:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ypp:raffle:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ypp:raffle:remove']"
        >删除</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ypp:raffle:export']"
        >导出</el-button>
      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="raffleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="抽奖活动" align="center" prop="configId" :formatter="configIdFormat" />
      <el-table-column label="奖品名称" align="center" prop="name" />
      <el-table-column label="奖品类型" align="center" prop="contentType" :formatter="contentTypeFormat" />
      <el-table-column label="中奖率(%)" align="center" prop="rate" />
      <el-table-column label="奖品总数量" align="center" prop="total" />
      <el-table-column label="中奖数量" align="center" prop="num" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span :class="'common_status_'+scope.row.status">{{statusFormat(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户端" align="center" prop="wxClientIdName" v-has-role="['admin']"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ypp:raffle:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ypp:raffle:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改抽奖活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">

        <el-form-item label="抽奖活动" prop="configId">
          <el-select v-model="form.configId" placeholder="请选择" @change="configChange">
            <el-option
              v-for="item in configOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="奖品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="中奖率(%)" prop="rate">
          <el-input-number v-model="form.rate" :min="1"  placeholder="请输入中奖率" >
          </el-input-number>
        </el-form-item>

        <el-form-item label="奖品类型" prop="contentType">
          <el-select v-model="form.contentType" placeholder="请选择类型">
            <el-option
              v-for="item in contentTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="parseInt(item.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="绑定奖品" prop="dataId" v-if="form.contentType==2">
          <el-select v-model="form.dataId" placeholder="请选择">
            <el-option
              v-for="item in qykOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="奖品总数量" prop="total">
          <el-input v-model="form.total" type="number" placeholder="请输入数量" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>

        <el-form-item label="图片上传" prop="imgPath">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :limit="1"
            :headers="headers"
          >
            <div v-if="form.imgPath" >
              <img :src="base_url+form.imgPath" class="avatar" width="100px" height="100px">
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRaffle, getRaffle, delRaffle, addRaffle, updateRaffle, exportRaffle } from "@/api/ypp/raffle";
import {getToken} from "@/utils/auth";
import { listConfig } from "@/api/ypp/config";
import { listQyk } from "@/api/wx/qyk";

export default {
  name: "Raffle",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 抽奖活动表格数据
      raffleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 奖品类型字典
      contentTypeOptions: [],
      // 状态字典
      statusOptions: [],
      configOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        rate: undefined,
        wxClientId: undefined,
        contentType: undefined,
        status: undefined,
        wxClientIdName: undefined,
        configId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        total: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        rate: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        contentType:[
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        configId:[
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        dataId:[
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      },
      base_url: process.env.VUE_APP_BASE_API,
      // 设置上传的请求头部
      headers: {Authorization: "Bearer " + getToken()},
      //上传地址
      url: process.env.VUE_APP_BASE_API + "/common/upload",
      filePaths: [],
      qykOptions: []
    };
  },
  created() {
    this.getList();
    this.getDicts("ypp_award_raffle_type").then(response => {
      this.contentTypeOptions = response.data;
    });
    this.getDicts("ypp_award_raffle_status").then(response => {
      this.statusOptions = response.data;
    });

    listConfig().then(response => {
      this.configOptions = response.rows;
    })

  },
  activated(){

  },
  deactivated(){

  },
  methods: {
    /** 查询抽奖活动列表 */
    getList() {
      this.loading = true;
      listRaffle(this.queryParams).then(response => {
        this.raffleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getQykList(wxClientId){
      this.qykOptions = [];
      listQyk({
        channel: "1",
        wxClientId: wxClientId
      }).then(response => {
        this.qykOptions = response.rows;
      })
    },
    // 内容类型：0优惠券，1积分字典翻译
    contentTypeFormat(row, column) {
      return this.selectDictLabel(this.contentTypeOptions, row.contentType);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    configIdFormat(row){
      let txt = '';
      this.configOptions.forEach(e=>{
        if(e.id == row.configId){
          txt = e.name;
          return;
        }
      });
      return txt;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        rate: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        wxClientId: undefined,
        contentType: undefined,
        status: "1",
        sort: "0",
        configId: undefined,
        dataId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加抽奖活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRaffle(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改抽奖活动";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.filePaths && this.filePaths.length>0){
            this.form.imgPath = this.filePaths[0];
          }
          if (this.form.id != undefined) {
            updateRaffle(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addRaffle(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除抽奖活动编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRaffle(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有抽奖活动数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportRaffle(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },

    handleAvatarSuccess(res, file,fileList){
      if (res.code == 200){
        this.form.imgPath = res.fileName;
      }
    },
    configChange(id){
      let that = this;
      this.configOptions.forEach(e=>{
        if(e.id == id){
          that.getQykList(e.wxClientId);
          return;
        }
      });
    }
  }
};
</script>
<style scoped>

  .avatar-uploader .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .avatar-uploader-icon:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
